//
//  SearchViewController.m
//  iMiniTao
//
//  Created by liu nian on 13-8-20.
//  Copyright (c) 2013年 liunian. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchCell.h"
#import "DataManager.h"
#import "SourceManager.h"
#import "ItemViewController.h"
#import "MobClick.h"

//频道背景颜色
#define COLOR_RGBA_SOURCE_BG  COLOR_RGBA(0, 174.0f, 238.0f, 0.6f)
#define COLOR_RGB_SOURCE_BG   COLOR_RGB(0, 174.0f, 238.0f)

#define COLOR_TABLECELL_SELECT_DAY      COLOR_RGB(234, 234, 234)
#define COLOR_TABLECELL_SELECT_NIGHT    COLOR_RGB(55, 55, 55)

#define COLOR_IMAGE_DEFAULT_BG        COLOR_RGB(221, 221, 221)
#define COLOR_IMAGE_DEFAULT_BG_NIGHT  COLOR_RGB(61, 61, 61)


@interface SearchViewController ()<UITextFieldDelegate,DataManagerDelegate,UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate>{
    NSInteger   _index;
    BOOL        _reload;
    BOOL        _loadMore;
    BOOL        _hasMore;
}
@property (nonatomic, retain) UITableView*tableView;
@property (nonatomic, retain) UIImageView          *navImageView;
@property (nonatomic, retain) UIImageView          *bgSearchImageView;
@property (nonatomic, retain) UITextField          *searchTextField;
@property (nonatomic, retain) NSMutableArray        *datasource;

@property (nonatomic, retain) UILabel *headerLabel;
@property (nonatomic, retain) UIButton *addBtn;
@property (nonatomic, retain) NSString  *keyword;

@end

@implementation SearchViewController

- (void)dealloc{
    [[DataManager sharedInstance] setDelegate:nil];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = COLOR_RGB(248, 248, 248);
    [self.view addSubview:self.navImageView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    tap.delegate = self;
    tap.numberOfTapsRequired= 1;
    [self.view addGestureRecognizer:tap];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)back
{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"搜索视图"];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"搜索视图"];
}
- (void)handleTap:(UITapGestureRecognizer *)tap{
    [self.searchTextField resignFirstResponder];
}

- (void)addKeyword{
    if ([[SourceManager sharedManager] isExistKeyword:self.keyword]) {
        [[SourceManager sharedManager] removeCustomSourceKeyWord:self.keyword];
    }else{

        CuzyTBKItem *item = [self.datasource objectAtIndex:0];
        [[SourceManager sharedManager] addCustomSourceKeyword:self.keyword icon:item.itemImageURLString];
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                              self.keyword, @"keyword", nil];
        [MobClick event:@"SubscribeCustomKey"  attributes:dict];
    }
    
    [self updateUI];
}

- (void)refreshBtnClick{
    [self reloadItems];
}

- (void)updateUI{
    if ([[SourceManager sharedManager] isExistKeyword:self.searchTextField.text]) {
        [self.headerLabel setText:@"点击按钮取消订阅"];
        [self.addBtn setBackgroundImage:IMGNAMED(@"btn_newok_light.png") forState:UIControlStateNormal];
        [self.addBtn setBackgroundImage:IMGNAMED(@"btn_newok.png") forState:UIControlStateHighlighted];
    }else{
        [self.headerLabel setText:@"点击按钮添加关键词到订阅栏目"];
        [self.addBtn setBackgroundImage:IMGNAMED(@"btn_newok.png") forState:UIControlStateNormal];
        [self.addBtn setBackgroundImage:IMGNAMED(@"btn_newok_light.png") forState:UIControlStateHighlighted];
    }
    
}
- (void)searchSourcesByKeyword
{
    [self.searchTextField resignFirstResponder];
    NSString  *keyword = self.searchTextField.text;
    
    if ([keyword length]<=0) {
        return;
    }
    self.keyword = keyword;
    [self reloadItems];
    
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                          keyword, @"keyword", nil];
    [MobClick event:@"SearchKey" attributes:dict];
}
- (void)tableViewDidScrollToTop{
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
}
- (void)reloadItems{
    if (_reload) {
        return;
    }
    _reload = YES;

    [[DataManager sharedInstance] requstTBKItemsWithKeyWord:self.keyword
                                                WithThemeID:nil
                                            WithPicSizeType:PicSize360
                                                   WithSort:nil
                                              WithPageIndex:0
                                               withDelegate:self];

}
- (void)reloadMoreItems{
    
    if (_loadMore) {
        return;
    }
    _loadMore = YES;
    _index++;
    [[DataManager sharedInstance] requstTBKItemsWithKeyWord:self.keyword
                                                WithThemeID:nil
                                            WithPicSizeType:PicSize360
                                                   WithSort:nil
                                              WithPageIndex:_index
                                                withDelegate:self];

}
#pragma mark DataManagerDelegate
-(void) updateViewForSuccess:(id)dataModel{
    
    NSMutableArray *items = dataModel;
    
    if (_reload) {
        _reload = NO;
        _index = 0;
        if ([items count] > 0) {
            [self.datasource removeAllObjects];
            [self.datasource addObjectsFromArray:items];
        }
        
    }
    if (items.count < 20) {
        _hasMore = NO;
    }else{
        _hasMore = YES;
    }
    
    if (_loadMore && [items count] > 0) {
        [self.datasource addObjectsFromArray:items];
        _loadMore = NO;
    }
    [self.tableView reloadData];
}
-(void) updateViewForError:(NSError *)errorInfo{
    if (_reload) {
        _reload = NO;
    }
    
    if (_loadMore) {
        _loadMore = NO;
        _index--;
    }
    [self.datasource removeAllObjects];
    [self.tableView reloadData];
}
#pragma mark UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {//如果当前是tableView
        //做自己想做的事
        return NO;
    }
    if ([touch.view isKindOfClass:[UITableViewCell class]] || [touch.view isKindOfClass: [UIButton class]] ){
            return NO;
        }
    return YES;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    // Return the number of rows in the section.
    return [self.datasource count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"SourceCell";
    
    SearchCell *cell = (SearchCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[SearchCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    
    CuzyTBKItem  *item = nil;
    item = [self.datasource objectAtIndex:indexPath.row];

    
    [cell.srcImageView setImageWithURL:[NSURL URLWithString:item.itemImageURLString] placeholderImage:nil];
    [cell.nameLabel setText:item.itemName];
    [cell.priceLabel setText:[NSString stringWithFormat:@"原价:%@",item.itemPrice]];
    [cell.promotionPriceLabel setText:[NSString stringWithFormat:@"折扣价:%@",item.promotionPrice]];
    return cell;
}

#pragma mark - Table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kSearchCellHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
	return 38.0f;
}

-(UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section {
    if (self.datasource.count > 0) {
        UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 38.0f)];
        [headerView setBackgroundColor:COLOR_RGB(248, 248, 248)];
        [headerView addSubview:self.headerLabel];
        [headerView addSubview:self.addBtn];
    
        UIImage  *imgLine = IMGNAMED(@"bg_cell_separator_line.png");
        UIImageView  *lineView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.headerLabel.bounds.size.height-imgLine.size.height, self.headerLabel.bounds.size.width, imgLine.size.height)];
        lineView.backgroundColor = [UIColor clearColor];
        lineView.image = imgLine;
        [self.headerLabel addSubview:lineView];
        [self updateUI];
        tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        return headerView;
    }else{
        UILabel   *headLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 38.0f)];
        headLabel.textAlignment = [Util getAlign:ALIGNTYPE_CENTER];
        headLabel.font = FONT_CONTENT(18.0f);
        headLabel.textColor = COLOR_RGB(211.0f, 211.0f, 211.0f);
        headLabel.backgroundColor = COLOR_RGB(248, 248, 248);
        UIImage  *imgLine = IMGNAMED(@"bg_cell_separator_line.png");
        headLabel.text = @"无搜索结果";
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        UIImageView  *lineView = [[UIImageView alloc] initWithFrame:CGRectMake(0, headLabel.bounds.size.height-imgLine.size.height, headLabel.bounds.size.width, imgLine.size.height)];
        lineView.backgroundColor = [UIColor clearColor];
        lineView.image = imgLine;
        [headLabel addSubview:lineView];

        return headLabel;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CuzyTBKItem  *item = nil;
    item = [self.datasource objectAtIndex:indexPath.row];
    ItemViewController *itemVC = [[ItemViewController alloc] initWithMeItem:item];
    [self.navigationController pushViewController:itemVC animated:YES];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.datasource.count - indexPath.row < 10 && !_loadMore && _hasMore) {
        [self reloadMoreItems];
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self searchSourcesByKeyword];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"]){
        return YES;
    }
    return YES;
    
}

#pragma mark - getter

- (UIImageView *)navImageView{
    if (!_navImageView) {
        _navImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 58)];
        _navImageView.userInteractionEnabled = YES;
        

        
        UIImage *imgBtn = IMGNAMED(@"bg_nav_button_small.png");
        UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
        back.exclusiveTouch = YES;
        back.frame = CGRectMake(10, (_navImageView.bounds.size.height-imgBtn.size.height)/2,
                                imgBtn.size.width, imgBtn.size.height);
        [back setBackgroundImage:imgBtn forState:UIControlStateNormal];
        [back setTitleColor:COLOR_RGB(0,0,0) forState:UIControlStateNormal];
        [back setTitle:@"关闭" forState:UIControlStateNormal];
        back.titleLabel.font = FONT_CONTENT(16.0f);
        [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        [_navImageView addSubview:back];
        
        UILabel  *title = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(back.frame) + 20,
                                                                    CGRectGetMinY(back.frame), 100, CGRectGetHeight(back.frame))];
        title.backgroundColor = [UIColor clearColor];
        title.textColor = COLOR_RGB(0, 0, 0);
        title.textAlignment = ALIGNTYPE_CENTER;
        title.font = FONT_TITLE(26.0f);
        title.text = @"搜索";
        [_navImageView addSubview:title];
        
        
        [_navImageView addSubview:self.bgSearchImageView];
        _navImageView.backgroundColor = COLOR_RGB_NAV;
        [_navImageView addSubview:self.bgSearchImageView];
    }
    return _navImageView;
}

- (UIImageView *)bgSearchImageView{
    if (!_bgSearchImageView) {
        UIImage  *imgBG = IMGFROMBUNDLE(@"bg_textfield_search.png");
        
        _bgSearchImageView = [[UIImageView alloc] initWithFrame:CGRectMake(230, 9, imgBG.size.width, imgBG.size.height)];
        _bgSearchImageView.backgroundColor = [UIColor redColor];
        _bgSearchImageView.userInteractionEnabled = YES;
        
        UIImage  *imgSearch = IMGFROMBUNDLE(@"bg_search.png");
        
        self.searchTextField.frame = CGRectMake(10, floorf((_bgSearchImageView.bounds.size.height-30)/2), imgBG.size.width-imgSearch.size.width-10, 30);
        [_bgSearchImageView addSubview:self.searchTextField];
        UIButton  *btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
        btnRight.frame = CGRectMake(_bgSearchImageView.bounds.size.width-imgSearch.size.width, floorf((_bgSearchImageView.bounds.size.height-imgSearch.size.height)/2), imgSearch.size.width, imgSearch.size.height);
        [btnRight setImage:imgSearch forState:UIControlStateNormal];
        [btnRight addTarget:self
                     action:@selector(searchSourcesByKeyword)
           forControlEvents:UIControlEventTouchUpInside];
        [_bgSearchImageView addSubview:btnRight];
        
        self.searchTextField.textColor = COLOR_RGB(0, 0, 0);
        _bgSearchImageView.image = IMGFROMBUNDLE(@"bg_textfield_search.png");
    }
    return _bgSearchImageView;
}

- (UITextField *)searchTextField{
    if (!_searchTextField) {
        _searchTextField = [[UITextField alloc] initWithFrame:CGRectZero];
        _searchTextField.borderStyle = UITextBorderStyleNone;
        _searchTextField.clearsOnBeginEditing = YES;
        _searchTextField.placeholder = @"请输入您感兴趣的关键词";
        _searchTextField.delegate = self;
        _searchTextField.font = FONT_CONTENT(14.0f);
        _searchTextField.rightViewMode = UITextFieldViewModeNever;
        _searchTextField.returnKeyType = UIReturnKeySearch;
        _searchTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        _searchTextField.autocorrectionType = UITextAutocorrectionTypeNo;
        _searchTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    }
    return _searchTextField;
}

- (UITableView *)tableView{
    if (nil == _tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,
                                                                   self.navImageView.frame.origin.y+self.navImageView.bounds.size.height,
                                                                   CGRectGetWidth(self.view.bounds),
                                                                   self.view.bounds.size.height -self.navImageView.frame.origin.y-self.navImageView.bounds.size.height)
                                                  style:UITableViewStylePlain];
        [_tableView setBackgroundColor:[UIColor clearColor]];
        [_tableView setDelegate: self];
        [_tableView setDataSource:self];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (NSMutableArray *)datasource{
    if (!_datasource) {
        _datasource = [[NSMutableArray alloc] initWithCapacity:20];
    }
    return _datasource;
}

- (UILabel *)headerLabel{
    if (!_headerLabel) {
        _headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, CGRectGetWidth(self.view.bounds) - 40, 38.0f)];
        _headerLabel.textAlignment = [Util getAlign:ALIGNTYPE_LEFT];
        _headerLabel.font = FONT_CONTENT(18.0f);
        _headerLabel.textColor = COLOR_RGB(211.0f, 211.0f, 211.0f);
        _headerLabel.backgroundColor = COLOR_RGB(248, 248, 248);
        _headerLabel.text = @"点击按钮添加关键词到订阅栏目";
    }
    return _headerLabel;
}

- (UIButton *)addBtn{
    if (!_addBtn) {
        UIImage *imgTop = IMGNAMED(@"btn_newok.png");
        _addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _addBtn.exclusiveTouch = YES;
        _addBtn.frame = CGRectMake(CGRectGetWidth(self.view.bounds)-imgTop.size.width-10, floorf((38-imgTop.size.height)/2), imgTop.size.width, imgTop.size.height);
        [_addBtn addTarget:self action:@selector(addKeyword) forControlEvents:UIControlEventTouchUpInside];
        [_addBtn setBackgroundImage:IMGNAMED(@"btn_newok.png") forState:UIControlStateNormal];
        [_addBtn setBackgroundImage:IMGNAMED(@"btn_newok_light.png") forState:UIControlStateHighlighted];
    }
    return _addBtn;
}
@end
